package ejb;

import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Announce;
import model.Citizen;
import model.Election;
import model.Governor;
import utils.AbstractBean;
import entitymanagers.AnnounceManager;

@Stateless
@LocalBean
public class AnnounceManagerBean extends AbstractBean<Announce> implements AnnounceManager{

	public AnnounceManagerBean() {
		super(Announce.class);
	}
	@PersistenceContext
	private EntityManager em;
	@Resource
	private SessionContext context;
	@EJB
	private TimeManager tm;
	@Override
	public void setCandidacyPeriod(Date startCandidacy, Date endCandidacy) {
		Announce announce = em.find(Announce.class, context.getCallerPrincipal().getName());
		if (announce!=null){
			Election election = new Election();;
			announce.setElection(election);
			election.setStartCandidacy(startCandidacy);
			election.setEndCandidacy(endCandidacy);
			em.merge(announce);
		}
		else{
			announce = new Announce();
			Election election = new Election();
		    announce.setElection(election);
			election.setStartCandidacy(startCandidacy);
			election.setEndCandidacy(endCandidacy);
			announce.setGovernor(em.find(Governor.class, context.getCallerPrincipal().getName()));
			em.persist(announce);
			
		}
		tm.setCandidacyPeriod(startCandidacy, endCandidacy);
		
	}

	@Override
	public void setDateElection(Date dateElection) {
		Announce announce = em.find(Announce.class, context.getCallerPrincipal().getName());
		if (announce!=null){
			Election election = new Election();
			announce.setElection(election);
			election.setDateElection(dateElection);
			announce.setGovernor(em.find(Governor.class, context.getCallerPrincipal().getName()));
			em.merge(announce);
		}
		else {
			announce = new Announce();
			Election election = new Election();
			announce.setElection(election);
			election.setDateElection(dateElection);
			announce.setGovernor(em.find(Governor.class, context.getCallerPrincipal().getName()));
			em.persist(announce);
		}
		tm.setDateElection(dateElection);
		
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	

}
